import axios from 'axios';
import { router } from '@/router/index.js'
import { ElMessage } from 'element-plus';

// 创建 Axios 实例
const http = axios.create({
    baseURL: 'http://localhost:8080/', // 设置你的后端 API 地址
    timeout: 8000
  });
  
  // 请求拦截器
  http.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;

    }
    return config;
  }, error => {
    return Promise.reject(error);
  });
  
  // 响应拦截器
  http.interceptors.response.use(response => {
    return response;
  }, error => {
    if (error.response.status === 401) {
      // Token 失效，跳转到登录页面
      localStorage.removeItem('token');
      localStorage.removeItem('role');
      console.log("token失效！")
      ElMessage.error('登录失效，请重新登录');
      router.push('/login');

    } else if (error.response.status === 403) {
      ElMessage.error('权限不足，请尝试重新登录或者联系管理员')
    }
    return Promise.reject(error);
  });
  
  export default http;